//
//  OAuthViewController.swift
//  02-TDD
//
//  Created by apple on 15/2/28.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

// 定义全局常量
let WB_Login_Successed_Notification = "WB_Login_Successed_Notification"

class OAuthViewController: UIViewController {

    private let WB_API_URL_String       = "https://api.weibo.com"
    private let WB_Redirect_URL_String  = "http://www.itheima.com"
    private let WB_Client_ID            = "2720451414"
    private let WB_Client_Secret        = "e061ff9a264a0bedb55226685b34c084"
    private let WB_Grant_Type           = "authorization_code"
    
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        loadAuthPage()
    }
    
    /// 加载授权页面
    private func loadAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL_String)"
        let url = NSURL(string: urlString)!
        
        webView.loadRequest(NSURLRequest(URL: url))
    }
}

extension OAuthViewController: UIWebViewDelegate {
    
    /// 页面重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let result = continueWithCode(request.URL!)
        
        if let code = result.code {
            let params = ["client_id": WB_Client_ID,
            "client_secret": WB_Client_Secret,
            "grant_type": WB_Grant_Type,
            "redirect_uri": WB_Redirect_URL_String,
            "code": code]

            let net = NetworkManager.sharedManager
            net.requestJSON(.POST, "https://api.weibo.com/oauth2/access_token", params) { (result, error) -> () in
                
                // 保存 token
                AccessToken(dict: result as! NSDictionary).saveAccessToken()
                
                // 登录成功通知
                NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil)
            }
        }
        
        // 只有点击取消按钮，才需要重新刷新授权页面
        if result.reloadPage {
            SVProgressHUD.showInfoWithStatus("真的要残忍拒绝吗？", maskType: SVProgressHUDMaskType.Gradient)
            loadAuthPage()
        }
        
        return result.load
    }
    
    ////  根据URL判断是否继续
    ///
    ///  :param: url URL
    ///
    ///  :returns: (是否加载当前页面, code, 是否刷新授权页面)
    private func continueWithCode(url: NSURL) -> (load: Bool, code: String?, reloadPage: Bool) {
        
        let urlString = url.absoluteString!
        
        // 如果是微博的 api 地址，继续
        if urlString.hasPrefix(WB_API_URL_String) {
            return (true, nil, false)
        }
        
        // 如果不是回调地址，不加载
        if !urlString.hasPrefix(WB_Redirect_URL_String) {
            return (false, nil, false)
        }
        
        // 检查查询字符串
        if let query = url.query as NSString? {
            let codeStr = "code="
            
            if query.hasPrefix(codeStr) {
                return (false, query.substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)), false)
            }
        }
        
        return (false, nil, true)
    }
}
